package com.open.capacity.exam.service.impl;

import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.exam.dao.QuestionDao;
import com.open.capacity.exam.service.QuestionOptionService;
import com.open.capacity.exam.service.QuestionService;
import com.open.capacity.exam.vo.QuestionsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private QuestionDao questionDao;
    @Autowired
    private QuestionOptionService optionService;

    /**
     * 条件查询
     * @param param
     * @return
     */
    @Override
    public PageResult<QuestionsVo> findAll(QuestionsVo param) {
        List<QuestionsVo> list = questionDao.findAll(param);
        int count= questionDao.findAllCount(param);
        return PageResult.<QuestionsVo>builder().data(list).count((long)count).build();
    }

    /**
     * 新增考题
     * @param param
     * @return
     */
    @Override
    @Transactional
    public Result addQuestions(QuestionsVo param) throws ServiceException {
        try {
            String optionA=param.getOptioA();
            String optioB = param.getOptioB();
            if(optionA!=null&&!optionA.equals("")&&optioB!=null&&!optioB.equals("")){
                Integer integer = optionService.addOption(param);//获取选项的id
                param.setQoptid(integer);
            }
            int insert= questionDao.insert(param);
            return insert>0?Result.succeed("添加成功"):Result.failed("操作失败");
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 修改考题类型
     * @param param
     * @return
     */
    @Override
    @Transactional
    public Result editQuestions(QuestionsVo param) {
        Integer qoptid = param.getQoptid();
        if(qoptid!=null&&!qoptid.equals("")){ //选项id存在选择题修改选项
            optionService.editOption(param);
        }
        Integer update= questionDao.update(param);
        return update>0?Result.succeed("修改成功"):Result.failed("操作失败");
    }

    /**
     * 获取考题阶段
     * @return
     */
    @Override
    public List<String> getStage() {
        return questionDao.findAllStage();
    }
}
